import { Avatar, Image, Spin, Trigger } from "@arco-design/web-react"
import { emojis } from "./input_box";
import { IconDriveFile, IconExclamation, IconExclamationCircle, IconFile, IconVideoCamera } from "@arco-design/web-react/icon";
import { ConversationType, MessageState, MessageType } from "../../../domain/im/entity";
import { useDispatch, useSelector } from "react-redux";
import { getTimeStringAutoShort2 } from "../../../domain/time";
import { fetchGroupMemberInfo } from "../../../store/features/group_member";
import { useContext, useEffect, useState } from "react";
import { formatFileSize } from "../util/size";
import axios from "axios";
import { createGroupMessageText, invitedUserJoin, removeUsersGroup, updateNameGroup } from "./SessionItem";
import { LeoAvatar } from "../../../components/leo_Avatar";
import { ChatContext } from "..";
import { UserModelElement } from "../../friend/components/user_model";
import { AddFriendModel } from "../../friend/components/add_friend";
import http from "../../../http";
import { addUser } from "../../../store/features/otherUser";


const renderEmoji = (text: string) => {
    let result = [];
    let i = 0;

    while (i < text.length) {
        let matched = false;
        for (const emoji of Object.keys(emojis)) {
            if (text.startsWith(emoji, i)) {
                result.push(
                    <img
                        key={i}
                        src={`/emojis/${emojis[emoji]}`}
                        alt={emoji}
                        className="w-6 cursor-pointer inline-block"
                    />
                );
                i += emoji.length;
                matched = true;
                break;
            }
        }
        if (!matched && i < text.length) {
            const charCode = text.charCodeAt(i);
            if (charCode === 10 || charCode === 13) {
                result.push(<br />);
                if (charCode === 13 && text.charCodeAt(i + 1) === 10) {
                    i++;
                }
            } else if (charCode == 32) {
                result.push(<span key={i} >&nbsp; </span>);
            } else {
                result.push(text[i]);
            }
            i++;
        }
    }

    return result;
};








export const MessageItem: React.FC<{ message: any, conversation: any }> = ({ message, conversation }) => {
    const { topRef } = useContext(ChatContext);
    const { user } = useSelector((state: any) => state.user.value);
    const isSelf = user.userId == message.from;

    const users = useSelector((state: any) => state.friend.value.users)


    const [userInfo, setUserInfo] = useState<any>();

    useEffect(() => {
        if (message.userInfo) {
            if (users) {
                const findUser = users.find((item: any) => item.userId === message.userInfo.userId);
                if (findUser) {
                    if (findUser.remark) {
                        setUserInfo({ ...message.userInfo, remark: findUser.remark })
                    } else {
                        setUserInfo(message.userInfo);
                    }
                } else {
                    setUserInfo(message.userInfo);
                }
            }
        }

        if (conversation.type == ConversationType.private) {
            if (users) {
                const findUser = users.find((item: any) => item.userId == conversation.targetId);
                if (findUser) {
                    setUserInfo(findUser)
                }
            }
        }

    }, [message, users])



    const calculateTimeDifference = (startTime: any, endTime: any) => {

        if (!startTime || !endTime) return <><span>被中断</span></>;
        // 计算毫秒数的差异
        const differenceInMilliseconds = endTime - startTime;

        // 将毫秒数转换为分钟数和秒数
        let minutes: any = Math.floor(differenceInMilliseconds / (1000 * 60));
        const seconds = Math.floor((differenceInMilliseconds % (1000 * 60)) / 1000);

        // 如果分钟数大于等于60，则将其转换为小时，并调整分钟数
        let hours = 0;
        if (minutes >= 60) {
            hours = Math.floor(minutes / 60);
            minutes = minutes % 60;
        }

        // 格式化输出时间
        const formattedTime = `${hours > 0 ? hours.toString().padStart(2, '0') + ':' : ''}${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

        return <span>通话时长<span className="ml-1">{formattedTime}</span></span>;
    };


    const [popupVisible, setPopupVisible] = useState(false);

    const [visibleAdd, setVisibleAdd] = useState(false);

    const clickAddFriend = () => {
        setPopupVisible(false);
        setVisibleAdd(true);
    }

    const popup = (
        <div className="bg-white py-5 px-5 rounded-xl  shadow-2xl">
            {userInfo && conversation.type == ConversationType.private && <UserModelElement clickAddFriend={clickAddFriend} userInfo={userInfo} />}
            {userInfo && conversation.type == ConversationType.group && <UserModelElement clickAddFriend={clickAddFriend} userInfo={userInfo} />}
        </div>

    )

    return <>




        {
            message.typeu == MessageType.updateNameGroup &&
            <>
                <div className="mt-3 flex flex-row justify-center text-gray-500">
                    {updateNameGroup(user, message)}
                </div>
            </>
        }
        {
            message.typeu == MessageType.removeUserGroup &&
            <>
                <div className="mt-3 flex flex-row justify-center text-gray-500">
                    {removeUsersGroup(user, message)}
                </div>
            </>
        }

        {
            message.typeu == MessageType.invitationGroup &&
            <>
                <div className="mt-3 flex flex-row justify-center text-gray-500">
                    {invitedUserJoin(user, message)}
                </div>
            </>

        }

        {
            message.typeu == MessageType.createGroup &&
            <>
                <div className="mt-3 flex flex-row justify-center text-gray-500">
                    {createGroupMessageText(user, message)}
                </div>
            </>

        }

        <div className={`flex flex-row w-full ${isSelf && 'flex-row-reverse'} p-[23px]`}>
            <div>
                {
                    isSelf == true && <LeoAvatar userPortrait={user.userPortrait} userName={user.nickName}></LeoAvatar>
                }

                {
                    userInfo && <AddFriendModel userInfo={userInfo} visibleAdd={visibleAdd} setVisibleAdd={setVisibleAdd} ></AddFriendModel>
                }
                <Trigger
                    popupVisible={popupVisible}
                    onVisibleChange={(visible) => setPopupVisible(visible)}
                    getPopupContainer={(): any => topRef && topRef.current}
                    popup={() => popup}
                    trigger={['click']}
                    position="rt"
                    clickToClose={false}>
                    {
                        isSelf != true && conversation.type == ConversationType.private &&
                        <LeoAvatar userPortrait={user.userPortrait} userName={user.nickName}></LeoAvatar>
                    }
                    {

                        isSelf != true && conversation.type == ConversationType.group && userInfo &&
                        <LeoAvatar userPortrait={userInfo.userPortrait} userName={userInfo.nickName} />
                    }
                </Trigger>
            </div>

            <div className={`${isSelf ? 'mr-[10px] text-left' : 'ml-[10px] text-left'} `}>
                <div className={` flex items-end flex-row text-[16px] ${isSelf && 'justify-end'}`}>

                    {
                        !isSelf && conversation.type == ConversationType.private ?
                            <div className="text-[16px] text-gray-400"> {conversation.userName} </div> : ''
                    }
                    {
                        !isSelf && conversation.type == ConversationType.group && userInfo ? <div className="text-[16px] text-gray-400">

                            {userInfo.remark ? userInfo.remark : userInfo.nickName} </div> : ''
                    }
                </div>


                <div className="flex flex-row items-center justify-start">

                    {
                        isSelf && message.state == MessageState.sending ? <div className="mt-[13px] mr-3"><Spin /></div> : ''
                    }

                    {
                        isSelf && message.state == MessageState.error ? <div className="mt-[13px] mr-3 w-5 h-5 bg-red-500  leading-5 rounded-full text-center"><IconExclamation className="text-white" /></div> : ''
                    }





                    {
                        message.typeu == MessageType.VerifiedBy &&
                        <div className={`inline-block  text-[16px] text-gray-800 px-[13px] py-[6px] mt-[10px] max-w-[400px] rounded-lg break-words ${isSelf ? 'bg-[#cfe7ff] ' : 'bg-white'}`}>
                            我通过了你的朋友验证请求，现在我们可以开始聊天了
                        </div>

                    }

                    {
                        message.typeu == MessageType.SightMsg &&
                        <video controls className="w-[300px] rounded-md mt-[10px]"
                            src={message.state == MessageState.sending ? `data:image/jpeg;base64,${JSON.parse(message.dataContent).base64edData}` : JSON.parse(message.dataContent).remoteMediaUrl}></video>
                    }
                    {
                        message.typeu == MessageType.ImgMsg && <>
                            {
                                message.typeu == MessageType.ImgMsg && message.state == MessageState.sending ?
                                    <Image
                                        className='mt-2 w-[200px]'
                                        src={`data:image/jpeg;base64,${JSON.parse(message.dataContent).base64edData}`}
                                        alt='lamp'
                                    /> : <Image
                                        className='mt-2 w-[200px] h-[200px] overflow-hidden'
                                        src={JSON.parse(message.dataContent).remoteMediaUrl}
                                        alt='lamp'
                                    />
                            }
                        </>
                    }

                    {
                        message.typeu == MessageType.VideoOffer &&
                        <div className={`inline-block  text-[16px] text-gray-800 px-[13px] py-[6px] mt-[10px] max-w-[400px] rounded-lg break-words ${isSelf ? 'bg-[#cfe7ff] ' : 'bg-white'}`}>
                            <IconVideoCamera className="mr-2"></IconVideoCamera>

                            {
                                JSON.parse(message.dataContent).state == 1 && <span>未应答</span>
                            }
                            {
                                JSON.parse(message.dataContent).state == 4 && <span>未应答</span>
                            }
                            {
                                JSON.parse(message.dataContent).state == 3 && <span>{!isSelf ? '已' : '被'}拒绝</span>
                            }
                            {
                                JSON.parse(message.dataContent).state == 2 && calculateTimeDifference(JSON.parse(message.dataContent).start_time, JSON.parse(message.dataContent).end_time)
                            }
                            {
                                JSON.parse(message.dataContent).state == 5 && <span>{isSelf ? '' : '对方'}已取消</span>
                            }
                        </div>

                    }
                    
                    {
                        message.typeu == MessageType.noticeGroup &&
                        <div className={`inline-block  text-[16px] text-gray-800 px-[13px] py-[6px] mt-[10px] max-w-[400px] rounded-lg break-words ${isSelf ? 'bg-[#cfe7ff] ' : 'bg-white'}`}>
                            群公告: {JSON.parse(message.dataContent).content}
                        </div>

                    }

                    {
                        message.typeu == MessageType.TxtMsg &&
                        <div className={`inline-block  text-[16px] text-gray-800 px-[13px] py-[6px] mt-[10px] max-w-[400px] rounded-lg break-words ${isSelf ? 'bg-[#cfe7ff] ' : 'bg-white'}`}>
                            {renderEmoji(JSON.parse(message.dataContent).content)}
                        </div>

                    }

                    {
                        message.typeu == MessageType.FileMsg &&
                        <div onClick={() => {
                            const remoteMediaUrl = JSON.parse(message.dataContent).remoteMediaUrl;

                            const fileName = JSON.parse(message.dataContent).name;

                            axios({
                                method: 'get',
                                url: remoteMediaUrl,
                                responseType: 'blob', // important
                            }).then(response => {
                                const blob = new Blob([response.data], { type: 'application/octet-stream' });
                                const downloadUrl = URL.createObjectURL(blob);

                                // 创建一个隐藏的可下载链接
                                const a = document.createElement('a');
                                a.href = downloadUrl;
                                a.download = fileName;
                                a.click();

                                // 清理 URL 对象
                                URL.revokeObjectURL(downloadUrl);
                            }).catch(error => {
                                console.error('Error downloading file:', error);
                            });

                        }} className={` cursor-pointer flex flex-row justify-between items-center  min-w-[250px] min-h-[70px] text-gray-800 px-[13px] py-[6px] mt-[10px] max-w-[400px] rounded-lg break-words ${isSelf ? 'bg-[#cfe7ff] ' : 'bg-white'}`}>
                            <div>
                                <div className="text-[14px] font-medium">{JSON.parse(message.dataContent).name}</div>
                                <div className="text-[12px] text-gray-400 mt-1">{formatFileSize(JSON.parse(message.dataContent).size)}</div>
                            </div>
                            <div>
                                <IconFile className="text-gray-400" style={{ fontSize: '40px' }} />
                            </div>
                        </div>
                    }

                </div>





            </div>
        </div>
    </>
}